package com.itany.springcloud.springcloudsso.controller;

import com.itany.springcloud.springcloudcommon.vo.ResponseResult;
import com.itany.springcloud.springcloudsso.exception.UserNotFoundException;
import com.itany.springcloud.springcloudsso.util.JWTUtil;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/sso")
public class LoginController {

    @ExceptionHandler(UserNotFoundException.class)
    public ResponseResult loginExceptionHandler(Exception e){
        return ResponseResult.fail(e.getMessage());
    }

    @RequestMapping("/login")
    public ResponseResult login(String username, String password, HttpServletResponse response) throws Exception {
        System.out.println("LoginController.login()");

        if("abc".equals(username)&&"123".equals(password)){
            Map<String,String> payload=new HashMap<String,String>();
            payload.put("username","abc");
            payload.put("password","123");

            String jwt= JWTUtil.getJWT(payload);

            System.out.println(jwt);
            Cookie cookie=new Cookie("token",jwt);
            cookie.setPath("/");
            response.addCookie(cookie);


            return ResponseResult.success("登录成功");
        }

        throw new UserNotFoundException("用户名或密码错误");


    }
}
